package com.study.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class _56 {

    public static void main(String[] args) {
        int[][] merge = merge(new int[][]{{1, 3}, {2, 6}, {8, 10}, {15, 18}});
        System.out.println(Arrays.deepToString(merge));


        ArrayList<Integer[]> list = new ArrayList<>();
    }

    public static int[][] merge(int[][] intervals) {
        if (intervals.length == 1) {
            return intervals;
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return Integer.compare(o1[0], o2[0]);
            }
        });

        List<int[]> cache = new ArrayList<>();

        int l = intervals[0][0];
        int r = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][1] <= r) {
                // 比R小
                continue;
            } else if (intervals[i][0] <= r) {
                // 比R大 但是 L比l小
                r = intervals[i][1];
            } else {
                // 否则不相交
                cache.add(new int[]{l, r});
                l = intervals[i][0];
                r = intervals[i][1];
            }
        }

        int[][] result = new int[cache.size()][2];

        for (int i = 0; i < cache.size(); i++) {
            result[i] = cache.get(i);
        }
        return result;
    }
}
